import axios from 'axios'
import { API_CONFIG } from './config/api'
import { useUserStore } from './stores/user'

// 创建 Axios 实例
const myAxios = axios.create({
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  withCredentials: true
})

// 不需要token的API路径
const NO_TOKEN_PATHS = [
  '/api/account/checkCode', // 验证码相关API
  '/api/account/login',     // 登录相关API
  '/api/account/register'   // 注册相关API
]

// 全局请求拦截器
myAxios.interceptors.request.use(
  function (config) {
    // 检查是否是不需要token的路径
    const isNoTokenPath = NO_TOKEN_PATHS.some(path => {
      return config.url?.startsWith(path)
    })
    
    // 如果不是不需要token的路径，则添加token
    if (!isNoTokenPath) {
      const userStore = useUserStore()
      const userInfo = userStore.getUserInfo()
      
      // 如果有token，则添加到请求头
      if (userInfo.token) {
        config.headers = config.headers || {}
        config.headers['Authorization'] = `Bearer ${userInfo.token}`
      }
    }
    
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// 全局响应拦截器
myAxios.interceptors.response.use(
  function (response) {
    // 可以在这里添加全局响应处理逻辑
    return response
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  }
)

export default myAxios
